<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="_hgg1Y3vl6FDA0y9ycG3MRMdmBljtivpN0MGPBl9Vks">
  <meta name="baidu-site-verification" content="code-BjkBUVTz39">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangduwei.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":true,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk | valine","storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

<script data-ad-client="ca-pub-8087648226243491" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  <meta name="description" content="一、What、Why（是什么、为什么）1.1 什么是分区存储了解传统的共享存储 (Shared Storage):  每个app有独立的存储空间Android&#x2F;data&#x2F;pkg其他应用不可见（Context.getExternalFileDir） 访问外部空间需要额外权限READ&#x2F;WRITE_EXTERNAL_STORAGE、获取存储权限的应用可以访问整个外部存储空间 应用卸载时，保存在外部存储空">
<meta property="og:type" content="article">
<meta property="og:title" content="Android分区存储">
<meta property="og:url" content="https://wangduwei.top/android-scoped-storage.html">
<meta property="og:site_name" content="嗅不到北的狗子">
<meta property="og:description" content="一、What、Why（是什么、为什么）1.1 什么是分区存储了解传统的共享存储 (Shared Storage):  每个app有独立的存储空间Android&#x2F;data&#x2F;pkg其他应用不可见（Context.getExternalFileDir） 访问外部空间需要额外权限READ&#x2F;WRITE_EXTERNAL_STORAGE、获取存储权限的应用可以访问整个外部存储空间 应用卸载时，保存在外部存储空">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangduwei.top/images/scoped_storage.png">
<meta property="og:image" content="https://wangduwei.top/images/scoped_storage_2.png">
<meta property="article:published_time" content="2021-08-25T12:22:34.000Z">
<meta property="article:modified_time" content="2021-08-26T13:17:02.050Z">
<meta property="article:author" content="wangduwei">
<meta property="article:tag" content="Android">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangduwei.top/images/scoped_storage.png">

<link rel="canonical" href="https://wangduwei.top/android-scoped-storage.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Android分区存储 | 嗅不到北的狗子</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-69Z1P1CBTV"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-69Z1P1CBTV');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9f3c7bb2232e1e3fda4c019e4a4406c0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="嗅不到北的狗子" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">嗅不到北的狗子</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangduwei.top/android-scoped-storage.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpeg">
      <meta itemprop="name" content="wangduwei">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="嗅不到北的狗子">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Android分区存储
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-08-25 20:22:34" itemprop="dateCreated datePublished" datetime="2021-08-25T20:22:34+08:00">2021-08-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-26 21:17:02" itemprop="dateModified" datetime="2021-08-26T21:17:02+08:00">2021-08-26</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/android-scoped-storage.html#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/android-scoped-storage.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="一、What、Why（是什么、为什么）"><a href="#一、What、Why（是什么、为什么）" class="headerlink" title="一、What、Why（是什么、为什么）"></a>一、What、Why（是什么、为什么）</h3><p>1.1 什么是分区存储<br>了解传统的共享存储 (Shared Storage):</p>
<ul>
<li>每个app有独立的存储空间Android/data/pkg其他应用不可见（Context.getExternalFileDir）</li>
<li>访问外部空间需要额外权限READ/WRITE_EXTERNAL_STORAGE、获取存储权限的应用可以访问整个外部存储空间</li>
<li>应用卸载时，保存在外部存储空间文件不会被删除。</li>
</ul>
<span id="more"></span>

<p>共享存储带来的问题</p>
<ul>
<li>数据安全</li>
<li>存储空间浪费，难以管理</li>
</ul>
<p>分区存储解决方案(Scoped Storage):</p>
<ul>
<li>必须通过Media Store API和Storage Access FrameWork访问文件系统。=&gt;对传统共享存储系统的一种强制约束</li>
<li>文件归属：操作自己创建的文件无需任何权限（自己创建的文件系统会记录此文件的归属app，应用卸载后清除该归属字段，重装后读取该文件仍需权限申请），非共享文件存入私有目录。=&gt;文件和应用挂钩，便于操作系统进行管理</li>
</ul>
<p>By The Way:<br>在Android-Q （API-29）中通过android:requestLegacyExternalStorage=”true”可以禁用分区存储<br>在Android-R （API-30）中必须使用分区存储<br>在Android-Q中完全禁用了File API，Android-R重新启用</p>
<h3 id="二、How（分区存储实践-数据的增、删、改、查）"><a href="#二、How（分区存储实践-数据的增、删、改、查）" class="headerlink" title="二、How（分区存储实践-数据的增、删、改、查）"></a>二、How（分区存储实践-数据的增、删、改、查）</h3><p>2.1 对媒体文件的增删改查：</p>
<ul>
<li>增查：新增操作无需任何权限。查询其他应用的媒体资源需要READ_EXTERNAL_STORAGE权限。查询自己应用创建的媒体资源无需权限，当应用卸载重装后，自己创建的资源也需要申请权限。</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">saveImageToAlbum</span><span class="params">(context: <span class="type">Context</span>, imageFile: <span class="type">File</span>, imageName: <span class="type">String</span>)</span></span>: <span class="built_in">Boolean</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> withContext(Dispatchers.IO) &#123;</span><br><span class="line">        <span class="keyword">val</span> contentValues = ContentValues().apply &#123;</span><br><span class="line">            put(MediaStore.Images.Media.DISPLAY_NAME, imageName)</span><br><span class="line">            put(MediaStore.Images.Media.DESCRIPTION, <span class="string">&quot;图片描述&quot;</span>)</span><br><span class="line">            put(MediaStore.Images.Media.MIME_TYPE, <span class="string">&quot;image/jpg&quot;</span>)</span><br><span class="line">            <span class="comment">// 文件待处理状态，本应用独占，其他应用暂时无法访问</span></span><br><span class="line">            <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) &#123;</span><br><span class="line">                put(MediaStore.Images.Media.IS_PENDING, <span class="number">1</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 插入数据库，获得uri</span></span><br><span class="line">        <span class="keyword">val</span> uri = context.contentResolver</span><br><span class="line">            .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)</span><br><span class="line">            ?: <span class="keyword">return</span><span class="symbol">@withContext</span> <span class="literal">false</span></span><br><span class="line">        <span class="comment">// 根据uri打开输出流，写入imageFile文件</span></span><br><span class="line">        context.contentResolver.openOutputStream(uri)?.use &#123; it.write(imageFile.readBytes()) &#125;</span><br><span class="line">        <span class="comment">// 切换文件待处理状态</span></span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) &#123;</span><br><span class="line">            contentValues.clear()</span><br><span class="line">            contentValues.put(MediaStore.Images.Media.IS_PENDING, <span class="number">0</span>)</span><br><span class="line">            context.contentResolver.update(uri, contentValues, <span class="literal">null</span>, <span class="literal">null</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span><span class="symbol">@withContext</span> <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<ul>
<li>删改：删改自己创建的媒体资源无需权限。删改其他应用创建的资源需要捕获RecoverableSecurityException异常后，向用户申请删除权限。</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">performDeleteImage</span><span class="params">(image: <span class="type">MediaStoreModel</span>)</span></span> &#123;</span><br><span class="line">    withContext(Dispatchers.IO) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            getApplication&lt;Application&gt;().contentResolver.delete(</span><br><span class="line">                image.contentUri,</span><br><span class="line">                <span class="string">&quot;<span class="subst">$&#123;MediaStore.Images.Media._ID&#125;</span> = ?&quot;</span>,</span><br><span class="line">                arrayOf(image.id.toString())</span><br><span class="line">            )</span><br><span class="line">        &#125; <span class="keyword">catch</span> (securityException: SecurityException) &#123;</span><br><span class="line">            <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q) &#123;</span><br><span class="line">               <span class="keyword">val</span> recoverableSecurityException = securityException <span class="keyword">as</span>? RecoverableSecurityException</span><br><span class="line">                        ?: <span class="keyword">throw</span> securityException</span><br><span class="line">               startIntentSenderForResult(</span><br><span class="line">                   recoverableSecurityException.userAction.actionIntent.intentSender,</span><br><span class="line">                   DELETE_PERMISSION_REQUEST,</span><br><span class="line">                   <span class="literal">null</span>,</span><br><span class="line">                   <span class="number">0</span>,</span><br><span class="line">                   <span class="number">0</span>,</span><br><span class="line">                   <span class="number">0</span>,</span><br><span class="line">                   <span class="literal">null</span>)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">throw</span> securityException</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>2.2 对文档的增删改查：<br>对外部文档的读写操作需要使用Storage Access FrameWork，通过各种Intent交由系统处理。更多实例见[参考资料2]</p>
<p>SAF存储的限制：</p>
<ul>
<li>Intent.ACTION_OPEN_DOCUMENT_TREE访问限制<ul>
<li>内部存储根目录</li>
<li>Download目录</li>
<li>Android/data/  和  Android/obb/</li>
</ul>
</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建文档-返回Uri再进行写入</span></span><br><span class="line"><span class="keyword">val</span> intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply &#123;</span><br><span class="line">    addCategory(Intent.CATEGORY_OPENABLE)</span><br><span class="line">    type = <span class="string">&quot;text/plain&quot;</span></span><br><span class="line">    putExtra(Intent.EXTRA_TITLE, <span class="string">&quot;test.txt&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//读取&amp;删改</span></span><br><span class="line"><span class="keyword">val</span> intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply &#123;</span><br><span class="line">    addCategory(Intent.CATEGORY_OPENABLE)</span><br><span class="line">    type = <span class="string">&quot;*/*&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//目录操作</span></span><br><span class="line"><span class="keyword">val</span> intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply &#123;</span><br><span class="line">    flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<p>2.3 批量操作<br>通过MediaStore静态方法创建修改请求，征求用户同意后进行操作。Android-R后新增的API，旧版需走回contentResolver.delete()操作</p>
<table>
<thead>
<tr>
<th>操作</th>
<th>解释</th>
</tr>
</thead>
<tbody><tr>
<td>createWriteRequest</td>
<td>向用户请求媒体文件组写入权限</td>
</tr>
<tr>
<td>createFavoriteRequest</td>
<td>用户将设备上指定的媒体文件标记为“收藏”的请求</td>
</tr>
<tr>
<td>createTrashRequest</td>
<td>用户将指定的媒体文件放入设备垃圾箱的请求。垃圾箱中的内容会在系统定义的时间段后被永久删除。</td>
</tr>
<tr>
<td>createDeleteRequest</td>
<td>用户立即永久删除指定的媒体文件</td>
</tr>
</tbody></table>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">val</span> uriList = <span class="comment">/* A collection of content URIs to modify. */</span></span><br><span class="line"><span class="keyword">val</span> pendingIntent = MediaStore.createWriteRequest(contentResolver,urisToModify)</span><br><span class="line"></span><br><span class="line"><span class="comment">// Launch a system prompt requesting user permission for the operation.</span></span><br><span class="line">startIntentSenderForResult(editPendingIntent.intentSender,</span><br><span class="line">                           EDIT_REQUEST_CODE, </span><br><span class="line">                           <span class="literal">null</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<h3 id="三、直接文件读写"><a href="#三、直接文件读写" class="headerlink" title="三、直接文件读写"></a>三、直接文件读写</h3><p>Android-11重新支持File对象访问文件的直接路径。<br>1、针对媒体文件<br>    - 归属于你应用的文件 和 你的私有目录 的文件 可以直接使用File API访问<br>    - 如果直接用File API访问没有权限的文件，抛出 FileNotFoundException<br>2、Media Store DATA 属性<br>DATA属性存储了媒体文件的绝对路径，在Android-10的时候废弃了该属性。由于Android-11又支持File对象，所以DATA属性也可以读取直接路径，但不一定有值。但是新增和更新操作不要再使用DATA了，请使用DISPLAY_NAME 和 RELATIVE_PATH 。</p>
<h3 id="四、另外一扇窗"><a href="#四、另外一扇窗" class="headerlink" title="四、另外一扇窗"></a>四、另外一扇窗</h3><p>对于一些特殊的App，例如文件管理器，备份等。可以申请所有文件访问权限<br>1.声明 MANAGE_EXTERNAL_STORAGE 权限<br>2.使用 ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION  将用户引导至一个系统设置页面进行授权</p>
<p>授权范围</p>
<ul>
<li>读写共享存储区的所有文件<ul>
<li>Media content （MediaStore）</li>
<li>Documents and other files （SAF）</li>
<li>Datasets （BlobStoreManager）</li>
</ul>
</li>
<li>MediaStore.Files数据库表</li>
<li>USB 和 SD卡 根目录</li>
<li>除 /Android/data/ 和 /sdcard/Android 之外的其他私有目录</li>
</ul>
<h3 id="五、应用截图"><a href="#五、应用截图" class="headerlink" title="五、应用截图"></a>五、应用截图</h3><table>
    <tr>
        <td><img src="../images/scoped_storage.png" width="200"/></td>
        <td><img src="../images/scoped_storage_2.png" width="200"/></td>
    </tr>
</table>
    </div>

    
    
    
        <div class="reward-container">
  <div>赏你一杯咖啡</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="wangduwei 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpeg" alt="wangduwei 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>wangduwei
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wangduwei.top/android-scoped-storage.html" title="Android分区存储">https://wangduwei.top/android-scoped-storage.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Android/" rel="tag"># Android</a>
          </div>

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/leetcode-list-add.html" rel="prev" title="LeetCode 两数相加">
      <i class="fa fa-chevron-left"></i> LeetCode 两数相加
    </a></div>
      <div class="post-nav-item">
    <a href="/android-target-30.html" rel="next" title="Android-11适配">
      Android-11适配 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
      <div class="tabs tabs-comment">
        <ul class="nav-tabs">
            <li class="tab"><a href="#comment-gitalk">gitalk</a></li>
            <li class="tab"><a href="#comment-valine">valine</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane gitalk" id="comment-gitalk">
              <div class="comments" id="gitalk-container"></div>
            </div>
            <div class="tab-pane valine" id="comment-valine">
              <div class="comments" id="valine-comments"></div>
            </div>
        </div>
      </div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81What%E3%80%81Why%EF%BC%88%E6%98%AF%E4%BB%80%E4%B9%88%E3%80%81%E4%B8%BA%E4%BB%80%E4%B9%88%EF%BC%89"><span class="nav-number">1.</span> <span class="nav-text">一、What、Why（是什么、为什么）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E3%80%81How%EF%BC%88%E5%88%86%E5%8C%BA%E5%AD%98%E5%82%A8%E5%AE%9E%E8%B7%B5-%E6%95%B0%E6%8D%AE%E7%9A%84%E5%A2%9E%E3%80%81%E5%88%A0%E3%80%81%E6%94%B9%E3%80%81%E6%9F%A5%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">二、How（分区存储实践-数据的增、删、改、查）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%9B%B4%E6%8E%A5%E6%96%87%E4%BB%B6%E8%AF%BB%E5%86%99"><span class="nav-number">3.</span> <span class="nav-text">三、直接文件读写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E5%8F%A6%E5%A4%96%E4%B8%80%E6%89%87%E7%AA%97"><span class="nav-number">4.</span> <span class="nav-text">四、另外一扇窗</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%94%E3%80%81%E5%BA%94%E7%94%A8%E6%88%AA%E5%9B%BE"><span class="nav-number">5.</span> <span class="nav-text">五、应用截图</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wangduwei"
      src="/images/avatar.jpeg">
  <p class="site-author-name" itemprop="name">wangduwei</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/duweiwang" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;duweiwang" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wangduwei8@gmail.com" title="E-Mail → mailto:wangduwei8@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wangduwei</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">53k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">48 分钟</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>



  <script>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id    : 31838,
      el    : 'wpac-rating',
      color : 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>












  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '16c7d02bc3ca2bae3d85',
      clientSecret: 'bfda6fb671841e71f55e41fdd3fb794c8dbf40b2',
      repo        : 'duweiwang.github.io',
      owner       : 'duweiwang',
      admin       : ['duweiwang'],
      id          : 'd447aeae799cb42a590f3bcf271edded',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '45lTcsdp8QJNGsmN5wEaOtV5-gzGzoHsz',
      appKey     : 'QsK8vR7pb8w0M1eIk7QE50yF',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>


  <!-- 页面点击小红心 -->
  
        <script type="text/javascript" src="/js/love.js"></script>
  
</body>
</html>
